<template>
  <div class="word-uploader">
    <!-- 示例说明 -->
    <!-- <WordImportExample @start-import="showExample = false" /> -->

    <el-upload ref="uploadRef" class="upload-demo" drag :auto-upload="false" :on-change="handleFileChange"
      :before-upload="beforeUpload" accept=".docx" :limit="1" :on-exceed="handleExceed">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将Word文档拖拽到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持 .docx 格式，文件大小不超过 10MB
        </div>
      </template>
    </el-upload>

    <!-- 文件信息 -->
    <div v-if="fileInfo" class="file-info">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>文件信息</span>
            <el-button type="primary" size="small" @click="parseDocument">
              解析文档
            </el-button>
          </div>
        </template>
        <div class="file-details">
          <p><strong>文件名:</strong> {{ fileInfo.name }}</p>
          <p><strong>文件大小:</strong> {{ formatFileSize(fileInfo.size) }}</p>
          <p><strong>文件类型:</strong> {{ fileInfo.type }}</p>
        </div>
      </el-card>
    </div>

    <!-- 解析进度 -->
    <div v-if="isParsing" class="parsing-progress">
      <el-progress :percentage="parseProgress" :status="parseStatus" />
      <p class="progress-text">{{ parseStatusText }}</p>
    </div>

    <!-- 解析结果 -->
    <div v-show="parseResult" class="parse-result">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 文档预览 -->
        <el-tab-pane label="文档预览" name="preview">
          <div class="preview-container">
            <div ref="previewContainer" class="word-preview"></div>
          </div>
        </el-tab-pane>


        <!-- 表格数据 -->
        <el-tab-pane v-if="parseResult.tables.length > 0" label="表格数据" name="tables">
          <div class="tables-content">
            <div class="tables-header">
              <h3>解析到的表格 ({{ parseResult.tables.length }}个)</h3>
              <el-button type="primary" @click="addAllTablesToCanvas" :disabled="!parseResult.tables.length">
                全部添加到画布
              </el-button>
            </div>
            <div v-for="(table, index) in parseResult.tables" :key="index" class="table-item">
              <div class="table-item-header">
                <h4>表格 {{ index + 1 }}</h4>
                <el-button type="primary" size="small" @click="addTableToCanvas(table, index)">
                  添加到画布
                </el-button>
              </div>
              <div class="table-container">
                <table class="word-table" border="1" cellpadding="8" cellspacing="0">
                  <colgroup v-if="table.columnWidths">
                    <col v-for="(width, colIndex) in table.columnWidths" :key="colIndex" :style="{ width: width }" />
                  </colgroup>
                  <thead v-if="table.headers">
                    <tr>
                      <th v-for="(header, colIndex) in table.headers" :key="colIndex">
                        {{ header }}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(row, rowIndex) in table.rows" :key="rowIndex">
                      <td v-for="(cell, colIndex) in row" :key="colIndex" :rowspan="cell.rowspan || 1"
                        :colspan="cell.colspan || 1" :class="{ 'table-header': cell.isHeader }"
                        :style="cell.width ? { width: cell.width } : {}">
                        <div v-html="cell.content"></div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { wordParserService, type WordParseResult, type TableData } from '@/services/wordParserService'
import { useFormDesignerStore } from '@/stores/formDesigner'
import { convertWordTablesToIFormTable } from '@/utils/tableDataConverter'
import { getComponentDefaultAttrs } from '@/components/IFormComponents/componentConfigs'


// Store实例
const formDesignerStore = useFormDesignerStore()

// 响应式数据
const uploadRef = ref()
const previewContainer = ref<HTMLElement>()
const fileInfo = ref<File | null>(null)
const isParsing = ref(false)
const parseProgress = ref(0)
const parseStatus = ref<'success' | 'exception' | 'warning' | ''>('')
const parseStatusText = ref('')
const parseResult = ref<WordParseResult>({
  html: '',
  tables: [],
  images: [],
  metadata: {
    wordCount: 0,
    pageCount: 0
  }
})
const activeTab = ref('preview')


// 文件变化处理
const handleFileChange = (file: { raw: File }) => {
  fileInfo.value = file.raw
  parseResult.value = {
    html: '',
    tables: [],
    images: [],
    metadata: {
      wordCount: 0,
      pageCount: 0
    }
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isValidType = file.type === 'application/msword' ||
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
    file.name.endsWith('.docx')

  if (!isValidType) {
    ElMessage.error('只能上传 .docx 格式的Word文档!')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  return false // 阻止自动上传
}

// 文件超出限制处理
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件，请先删除当前文件')
}

// 格式化文件大小
const formatFileSize = (size: number): string => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  return (size / 1024 / 1024).toFixed(2) + ' MB'
}

// 解析文档
const parseDocument = async () => {
  if (!fileInfo.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  isParsing.value = true
  parseProgress.value = 0
  parseStatus.value = ''
  parseStatusText.value = '开始解析文档...'

  try {
    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (parseProgress.value < 90) {
        parseProgress.value += Math.random() * 20
        parseStatusText.value = '正在解析文档内容...'
      }
    }, 200)

    // 解析Word文档
    const result = await wordParserService.parseWordDocument(fileInfo.value)

    clearInterval(progressInterval)
    parseProgress.value = 100
    parseStatus.value = 'success'
    parseStatusText.value = '解析完成!'

    parseResult.value = result


    // 预览文档
    if (previewContainer.value) {
      await wordParserService.previewWordDocument(fileInfo.value, previewContainer.value)
    }

    ElMessage.success('文档解析成功!')

  } catch (error) {
    console.error('文档解析失败:', error)
    parseStatus.value = 'exception'
    parseStatusText.value = '解析失败'
    ElMessage.error('文档解析失败: ' + (error as Error).message)
  } finally {
    isParsing.value = false
  }
}

// 添加单个表格到画布
const addTableToCanvas = (table: TableData, index: number) => {
  try {
    // 转换Word表格数据为IFormTable格式
    const convertedTables = convertWordTablesToIFormTable([table])

    if (convertedTables.length === 0) {
      ElMessage.warning('表格数据为空，无法添加到画布')
      return
    }

    const convertedTable = convertedTables[0]

    // 获取表格组件的默认属性
    const defaultAttrs = getComponentDefaultAttrs('table')

    // 创建表格字段
    const tableField = {
      name: 'IFormTable',
      nickName: `表格 ${index + 1}`,
      type: 'table',
      icon: 'IFormTable',
      parentId: null,
      slot: null,
      isShow: true,
      attrs: {
        ...defaultAttrs,
        label: `表格 ${index + 1}`,
        tableData: convertedTable.tableData,
        columns: convertedTable.columns,
        border: true,
        stripe: false,
        size: 'default',
        showHeader: convertedTable.showHeader,
        highlightCurrentRow: false,
        emptyText: '暂无数据',
        showSummary: false
      },
      style: {
        width: Number(convertedTable.width) || 600,
        height: Number(convertedTable.height) || 300,
        x: 50 + (index * 50), // 错开位置
        y: 50 + (index * 50)
      },
      validation: false as const
    }

    // 添加到画布
    const addedField = formDesignerStore.addField(tableField)

    ElMessage.success(`表格 ${index + 1} 已添加到画布`)

    // 选中新添加的表格
    formDesignerStore.selectField(addedField)

  } catch (error) {
    console.error('添加表格到画布失败:', error)
    ElMessage.error('添加表格到画布失败: ' + (error as Error).message)
  }
}

// 添加所有表格到画布
const addAllTablesToCanvas = () => {
  if (!parseResult.value.tables.length) {
    ElMessage.warning('没有表格数据可添加')
    return
  }

  try {
    // 转换所有Word表格数据为IFormTable格式
    const convertedTables = convertWordTablesToIFormTable(parseResult.value.tables)

    let addedCount = 0

    convertedTables.forEach((convertedTable, index) => {
      // 获取表格组件的默认属性
      const defaultAttrs = getComponentDefaultAttrs('table')

      // 创建表格字段
      const tableField = {
        name: 'IFormTable',
        nickName: `表格 ${index + 1}`,
        type: 'table',
        icon: 'IFormTable',
        parentId: null,
        slot: null,
        isShow: true,
        attrs: {
          ...defaultAttrs,
          label: `表格 ${index + 1}`,
          tableData: convertedTable.tableData,
          columns: convertedTable.columns,
          border: true,
          stripe: false,
          size: 'default',
          showHeader: convertedTable.showHeader,
          highlightCurrentRow: false,
          emptyText: '暂无数据',
          showSummary: false
        },
        style: {
          width: Number(convertedTable.width) || 600,
          height: Number(convertedTable.height) || 300,
          x: 50 + (index * 50), // 错开位置
          y: 50 + (index * 50)
        },
        validation: false as const
      }

      // 添加到画布
      formDesignerStore.addField(tableField)
      addedCount++
    })

    ElMessage.success(`成功添加 ${addedCount} 个表格到画布`)

  } catch (error) {
    console.error('添加表格到画布失败:', error)
    ElMessage.error('添加表格到画布失败: ' + (error as Error).message)
  }
}

</script>

<style scoped lang="scss">
.word-uploader {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: scroll;


  .test-section {
    margin-bottom: 20px;
    text-align: center;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px dashed #d9d9d9;
  }

  .upload-demo {
    margin-bottom: 20px;
  }

  .file-info {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .file-details {
      p {
        margin: 8px 0;
        color: #666;
      }
    }
  }

  .parsing-progress {
    margin-bottom: 20px;
    text-align: center;

    .progress-text {
      margin-top: 10px;
      color: #666;
    }
  }

  .parse-result {
    flex: 1;
    display: flex;
    flex-direction: column;

    .el-tabs {
      flex: 1;
      display: flex;
      flex-direction: column;

      .el-tabs__content {
        flex: 1;
        overflow: hidden;
      }

      .el-tab-pane {
        height: 100%;
        overflow-y: auto;
      }
    }

    .preview-container {
      height: 100%;
      box-sizing: border-box;
      overflow-y: auto;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 15px;
      background: #fff;
    }


    .tables-content {
      .tables-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 6px;
        border: 1px solid #e4e7ed;

        h3 {
          margin: 0;
          color: #303133;
          font-size: 16px;
          font-weight: 600;
        }
      }

      .table-item {
        margin-bottom: 20px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        overflow: hidden;

        .table-item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 20px;
          background: #f5f7fa;
          border-bottom: 1px solid #e4e7ed;

          h4 {
            margin: 0;
            color: #303133;
            font-size: 14px;
            font-weight: 600;
          }
        }

        .table-container {
          overflow-x: auto;
          padding: 20px;

          .word-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
            background: white;

            th,
            td {
              border: 1px solid #e4e7ed;
              padding: 8px 12px;
              text-align: left;
              vertical-align: top;
              word-wrap: break-word;
              max-width: 200px;
            }

            th {
              background-color: #f5f7fa;
              font-weight: 600;
              color: #303133;
            }

            td.table-header {
              background-color: #f0f9ff;
              font-weight: 500;
            }

            tr:nth-child(even) {
              background-color: #fafafa;
            }

            tr:hover {
              background-color: #f0f9ff;
            }
          }
        }
      }
    }

  }
}

// Word预览样式
:deep(.word-preview) {
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  line-height: 1.6;
  color: #333;

  table {
    border-collapse: collapse;
    width: 100%;
    margin: 10px 0;

    td,
    th {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f5f5f5;
      font-weight: bold;
    }
  }

  p {
    margin: 8px 0;
  }

  img {
    max-width: 100%;
    height: auto;
  }
}
</style>
